--[[
	背包界面
	2016_07_06 Ravioyla
]]

local NoticeLayer = class("NoticeLayer", function(scene)
		local bagLayer = display.newLayer(cc.c4b(0, 0, 0, 180))
    return bagLayer
end)
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
local HeadSprite = appdf.req(appdf.EXTERNAL_SRC .. "HeadSprite")
local utils = appdf.req(appdf.EXTERNAL_SRC .. "Utils")

NoticeLayer.BT_NOTICEMAIL = 10
NoticeLayer.BT_MYMAIL = 11
NoticeLayer.BT_DELETMYMAIL = 12

-- 进入场景而且过渡动画结束时候触发。
function NoticeLayer:onEnterTransitionFinish()
		--自动跳转
	
    return self
end

-- 退出场景而且开始过渡动画时候触发。
function NoticeLayer:onExitTransitionStart()
	
	local sort_func = function(a, b) 
		local as = a.status or 0
		local bs = b.status or 0
		local aidx = a.idx
		local bidx = b.idx
		if as == bs and as == 0 then
			return aidx > bidx
		else
			return as < bs 
		end
		
	end  
	table.sort(self.Mymail_tab,sort_func) 
	self:updataMyMailTable()
    return self
end

function NoticeLayer:ctor(scene)
	self.scene = scene
	self:registerScriptHandler(function(eventType)
		if eventType == "enterTransitionFinish" then	-- 进入场景而且过渡动画结束时候触发。
			self:onEnterTransitionFinish()
		elseif eventType == "exitTransitionStart" then	-- 退出场景而且开始过渡动画时候触发。
			self:onExitTransitionStart()
        elseif eventType == "exit" then
        
		end
	end)


	scene._LogonFrame:sendGetNOtice()
		self.issendMymail = false  --控制切换到时候重复请求数据
		local rootLayer, csbNode = ExternalFun.loadRootCSB( "notice/NoticeLayer.csb", self )
		self.csbNode = csbNode
		
		self.csbNode:setPositionY((display.height-750)/2)
		csbNode:getChildByName("Button_18"):addTouchEventListener(function(ref,type) 
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect( )
			local bRedPoint = false
			for k,v in ipairs(self.noticeMail_tab) do
				if v.status == 0 then
					bRedPoint = true
				end
			end
			for k,v in ipairs(self.Mymail_tab) do
				if not v.status or v.status == 0 then
					bRedPoint = true
				end
			end
			scene.msgRedPointSp:setVisible(bRedPoint)

			scene:onKeyBack()
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
		end)
	local btcallback = function (ref, type)
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect( )
			self:onButtonClickedEvent(ref:getTag(),ref)
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
	end

	self.notice_btn = csbNode:getChildByName("notice_btn")
	self.myMail_btn = csbNode:getChildByName("myMail_btn")

	

	self.notice_Panel = csbNode:getChildByName("notice_Panel")
	self.myMail_Panel = csbNode:getChildByName("myMail_Panel")
	self.deletweidu = self.myMail_Panel:getChildByName("deletmail")
	self.deletweidu:setVisible(false)
	self.notic_listView = self.notice_Panel:getChildByName("notice_listview")
	self.notice_btn:setEnabled(false)
	self.notice_Panel:setVisible(true)
	self.isNoticeMail = true
	self.myMail_btn:setEnabled(true)
	self.myMail_Panel:setVisible(false)
	self.notice_btn:setTag(NoticeLayer.BT_NOTICEMAIL)
	self.myMail_btn:setTag(NoticeLayer.BT_MYMAIL)
	self.deletweidu:setTag(NoticeLayer.BT_DELETMYMAIL)
	self.notice_btn:addTouchEventListener(btcallback)
	self.myMail_btn:addTouchEventListener(btcallback)
	self.deletweidu:addTouchEventListener(btcallback)

	self.myMailDemo = csbNode:getChildByName("myMailDemo")
	self.noticeMailDemo = csbNode:getChildByName("noticeMailDemo")
	
	self.notice_Panel = csbNode:getChildByName("notice_Panel")
	self.notice_Panel:setLocalZOrder(5)
	self.myMail_Panel = csbNode:getChildByName("myMail_Panel")
	self.myMail_Panel:setLocalZOrder(5)

	ExternalFun.FixScaleUI(self.myMail_Panel)
	
	self.noticeMailInfo = csbNode:getChildByName("noticeMailInfo")
	self.mymailMailInfo = csbNode:getChildByName("mymailMailInfo")
	self.mymailMailInfo:setLocalZOrder(6)
	self.noticeMailInfo:setLocalZOrder(6)
	self.noticeNomailsp =  self.notice_Panel:getChildByName("nomailsp")
	self.myMailNomailsp =  self.myMail_Panel:getChildByName("nomailsp")
	
	self.noticeNomailsp:setVisible(false)
	self.myMailNomailsp:setVisible(false)
	
	self.noticeMailInfo:getChildByName("anima_panel"):getChildByName("closebt"):addTouchEventListener(function(ref,type) 
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect( )
			self.noticeMailInfo:setVisible(false)
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
	end)
	
	self.mymailMailInfo:getChildByName("anima_panel"):getChildByName("closebt"):addTouchEventListener(function(ref,type) 
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect( )
			self.mymailMailInfo:setVisible(false)
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
	end)

	self.noticeMail_tab = {}
	self.Mymail_tab = {}

	local mymailstr = cc.FileUtils:getInstance():getStringFromFile(device.writablePath .."myMail.txt")
	if mymailstr ~= "" then
		self.Mymail_tab = cjson.decode(mymailstr)
	end
	--self:updataNoticeMailTable(data)
	self.mailmaxid = cc.UserDefault:getInstance():getIntegerForKey("mymailMaxIdx", 0)
	self:loadMail()
	if scene.msgRedPointSp:isVisible() then
		self:onButtonClickedEvent(NoticeLayer.BT_MYMAIL,self.myMail_btn)
	end
end
--把公告数据更新到本地
function NoticeLayer:updataNoticeMailTable(recJson)
	self.noticeMail_tab = {}
		local maxIdx = 0
		if recJson and recJson.result ~= 0 then

			for i =1,#recJson.list do
				table.insert(self.noticeMail_tab,recJson.list[i])
			end
		end
		if #self.noticeMail_tab == 0 then
			self.noticeNomailsp:setVisible(true)
		else
			self.noticeNomailsp:setVisible(false)
		end
	
end
--把我的邮件数据更新到本地
function NoticeLayer:updataMyMailTable(recJson)
	
		local maxIdx = cc.UserDefault:getInstance():getIntegerForKey("mymailMaxIdx", 0)
		if recJson and recJson.result ~= 0 then
			for i =1,#recJson.list do
				table.insert(self.Mymail_tab,recJson.list[i])
				if recJson.list[i].idx > maxIdx  then
					maxIdx = recJson.list[i].idx
				end
			end
		end
		if #self.Mymail_tab == 0 then
			self.myMailNomailsp:setVisible(true)
			self.deletweidu:setVisible(false)
		else
			self.myMailNomailsp:setVisible(false)
			self.deletweidu:setVisible(true)
		end
		cc.UserDefault:getInstance():setIntegerForKey("mymailMaxIdx", maxIdx)
		self.mailmaxid = maxIdx
		cc.FileUtils:getInstance():writeStringToFile(cjson.encode(self.Mymail_tab),device.writablePath .."myMail.txt")
	
end

function NoticeLayer:onButtonClickedEvent(tag,ref)
	if tag == NoticeLayer.BT_NOTICEMAIL then
			self.notice_btn:setEnabled(false)
			self.myMail_btn:setEnabled(true)

			self.notice_Panel:setVisible(true)
			self.myMail_Panel:setVisible(false)
			self.isNoticeMail = true
			self:refrashNoticeListview()
	elseif tag == NoticeLayer.BT_MYMAIL then
			self.notice_btn:setEnabled(true)
			self.myMail_btn:setEnabled(false)
		
			self.notice_Panel:setVisible(false)
			self.myMail_Panel:setVisible(true)
			self.isNoticeMail = false
			if not self.issendMymail then
				self.scene._LogonFrame:sendGetMyMail(cc.UserDefault:getInstance():getIntegerForKey("mymailMaxIdx", 0))
			end
			self.issendMymail = true
			self:loadMail()
	elseif tag == NoticeLayer.BT_DELETMYMAIL then
		local isdel = false
		for i=#self.Mymail_tab, 1, -1 do 
            if self.Mymail_tab[i].status == 1 then 
				table.remove(self.Mymail_tab,i) 
				isdel = true
            end 
		end 
		if isdel then
			showToast(self,"删除已读邮件成功",1)
			local sort_func = function(a, b) 
				
				return a.idx > b.idx 
			end  
			table.sort(self.Mymail_tab,sort_func) 
		else
			showToast(self,"没有已读邮件",1)
		end
		self:loadMail()
	end
end
function NoticeLayer:refrashNoticeListview()
	self.notic_listView:removeAllItems()
	for k,v in ipairs(self.noticeMail_tab) do
		local item = self.noticeMailDemo:clone()
		local time_text  = item:getChildByName("time_text") 
		local mailContent_text  = item:getChildByName("mailContent") 
		
		time_text:setString(v.createtime)
		mailContent_text:setString(v.title)
		item:addTouchEventListener(function(ref,type) 
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect( )
			self:ClickMailCell(k)
			ref:setScale(1)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then  
			ref:setScale(1)
		end
		end)
		self.notic_listView:pushBackCustomItem(item)
	end
end
function NoticeLayer:loadMail()
	if not self.Mail_listview  then
		self.Mail_listview = cc.TableView:create(cc.size(993,514))
		self.Mail_listview:setAnchorPoint(cc.p(0,0))
		self.Mail_listview:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
		self.Mail_listview:setPosition(cc.p(0,85))
		self.Mail_listview:setDelegate()
		self.Mail_listview:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN)
		self.Mail_listview:registerScriptHandler(handler(self, self.cellSizeForTable), cc.TABLECELL_SIZE_FOR_INDEX)
		self.Mail_listview:registerScriptHandler(handler(self, self.tableCellAtIndex), cc.TABLECELL_SIZE_AT_INDEX)
		self.Mail_listview:registerScriptHandler(handler(self, self.numberOfCellsInTableView), cc.NUMBER_OF_CELLS_IN_TABLEVIEW)
		self.Mail_listview:registerScriptHandler(handler(self, self.tableCellTouched), cc.TABLECELL_TOUCHED)
		self.myMail_Panel:addChild(self.Mail_listview,5)
	end

	self.Mail_listview:reloadData()
	
end

--点击mail的cell
function NoticeLayer:ClickMailCell(idx,cell)
	
	if self.isNoticeMail then
		self:showNoticeInfo(self.noticeMail_tab[idx])
	else
		local weidu_img = cell:getChildByName("mail_item"):getChildByName("weidu_img")
		local yidu_img = cell:getChildByName("mail_item"):getChildByName("yidu_img")
		local letter_img = cell:getChildByName("mail_item"):getChildByName("letterimg")
		letter_img:loadTexture("notice/letteropen.png")
		weidu_img:setVisible(false)
		yidu_img:setVisible(true)
		
		self.Mymail_tab[idx].status = 1
		
		self:updataMyMailTable()
		self:showMailInfo(self.Mymail_tab[idx])

	end

end
function NoticeLayer:showNoticeInfo(infoData)
	local anima_panel = self.noticeMailInfo:getChildByName("anima_panel")
	ExternalFun.playOpenLayerAnimation( anima_panel )
	self.noticeMailInfo:setVisible(true)
	local content_text = anima_panel:getChildByName("content_text")
	content_text:setString("   "..infoData.content)
end

function NoticeLayer:showMailInfo(infoData)
	self.mymailMailInfo:setVisible(true)
	local anima_panel = self.mymailMailInfo:getChildByName("anima_panel")
	ExternalFun.playOpenLayerAnimation( anima_panel )
	local content_text = anima_panel:getChildByName("content_text")
	local createtime_text = anima_panel:getChildByName("time_text")
	content_text:setString("   "..infoData.content)
	createtime_text:setString(infoData.createtime)
end
function NoticeLayer:tableCellTouched(view, cell)
	ExternalFun.playClickEffect( )
	self:ClickMailCell(cell:getIdx()+1,cell)
end

function NoticeLayer:numberOfCellsInTableView( view )

	return #self.Mymail_tab

end
function NoticeLayer:cellSizeForTable( view, idx )
	return 989,168
end
function NoticeLayer:tableCellAtIndex( view, idx )
	local cell = view:dequeueCell()
	local itemData = nil
	local item = nil

	itemData = self.Mymail_tab[idx+1]
	if nil == cell then
		cell = cc.TableViewCell:new()

		item = self.myMailDemo:clone()
		item:addTouchEventListener(function(ref,type) 
			if type == ccui.TouchEventType.ended then
				ref:setScale(1)
			elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
			elseif type == ccui.TouchEventType.canceled then
			ref:setScale(1)
			end
		end)
		item:setSwallowTouches(false)
		item:setName("mail_item")
		item:setVisible(true)
		item:setPosition(cc.p(494.5,76))
		cell:addChild(item)
		
	else
		
		item = cell:getChildByName("mail_item")

	end
	if not self.isNoticeMail then
			local weidu_img = item:getChildByName("weidu_img")
			local yidu_img =  item:getChildByName("yidu_img")
			local letter_img = item:getChildByName("letterimg")
			letter_img:ignoreContentAdaptWithSize(true)
		if itemData.status then  --0是未读 1是已读
			weidu_img:setVisible(false)
			yidu_img:setVisible(true)
			letter_img:loadTexture("notice/letteropen.png")
		else 
			letter_img:loadTexture("notice/letterclose.png")
			weidu_img:setVisible(true)
			yidu_img:setVisible(false)
		end
	end
		
	local time_text  = item:getChildByName("time_text") 
	local mailContent_text = item:getChildByName("mailContent") 
	local send_text = item:getChildByName("send_text") 
	send_text:setString("发件人："..itemData.sender)
	time_text:setString(itemData.createtime)
	mailContent_text:setString(itemData.title)
	return cell
end

function NoticeLayer:DeletSystemMail(mailID,idx)
	local PostTabel ={}
		PostTabel.uid = GlobalUserItem.dwUserID
		PostTabel.type = 1
		PostTabel.id = mailID
		PostTabel.password = GlobalUserItem.szDynamicPass
		self:getParent():showPopWait()
		local  params = utils.genSig(PostTabel)
		appdf.onHttpJsionTable(CONSULTDEL_url,"POST",params,function(jsdata,jstable)
			if jsdata and jsdata.code == 0 then
					for k,v in ipairs(self.allMailData) do
						if v.id == self.mySystemMailTable[idx].id then
							table.remove(self.mySystemMailTable,idx) 
							table.remove(self.allMailData,k) 
							self.myFeedback_listview:reloadData()
						end
					end
					cc.FileUtils:getInstance():writeStringToFile(cjson.encode(self.allMailData),device.writablePath .."Allmail.txt")
					self.myFeedback_listview:reloadData()
	
				
				
			end
			self:getParent():dismissPopWait()
		end)
end

function NoticeLayer:DeletFeedBackMail(mailID,idx)
	local PostTabel ={}
		PostTabel.uid = GlobalUserItem.dwUserID
		PostTabel.type = 1
		PostTabel.id = mailID
		PostTabel.password = GlobalUserItem.szDynamicPass
		self:getParent():showPopWait()
		local  params = utils.genSig(PostTabel)
		appdf.onHttpJsionTable(CONSULTDEL_url,"POST",params,function(jsdata,jstable)
			if jsdata and jsdata.code == 0 then
		for k,v in ipairs(self.allMailData) do
						if v.id == self.myFeedBackMailTable[idx].id then
						
							table.remove(self.allMailData,k) 
							table.remove(self.myFeedBackMailTable,idx) 
			                self.myFeedback_listview:reloadData()
						end
					end
					cc.FileUtils:getInstance():writeStringToFile(cjson.encode(self.allMailData),device.writablePath .."Allmail.txt")
					self.myFeedback_listview:reloadData()
				
				
			end
			self:getParent():dismissPopWait()
		end)
end

return NoticeLayer